package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import dao.LearningMethodDAO;

/**
 * Servlet implementation class LearningMethodData
 */
public class LearningMethodData extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LearningMethodData() {
		super();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-cache");
		try {
			Map<Long, String> methods = LearningMethodDAO.getAll();
			PrintWriter outWriter = response.getWriter();
			JSONObject methodsList = new JSONObject();
			JSONArray jsonList = new JSONArray();

			for (Long methodId : methods.keySet()) {
				JSONObject jsonMethod = new JSONObject();
				jsonMethod.put("key", methodId);
				jsonMethod.put("nameValue", methods.get(methodId));
				jsonList.add(jsonMethod);
			}
			methodsList.put("methods", jsonList);
			outWriter.write(methodsList.toString());
		} catch (Throwable theException) {
			System.out.println(theException);
		}
	}

}
